package com.xhwl.centiotdata.suppliersystem.haikang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.HaiKangConstant;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.haikang.DoorHaiKangDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/14/ 09:00
 */
@Service
public class DeviceHaiKangHandler {
    private static final Logger log = LoggerFactory.getLogger(DeviceHaiKangHandler.class);

    @Autowired
    private GeneralHaiKangHandler generalHaiKangHandler;

    // 获取门禁
    public List<DoorHaiKangDTO> pullDoor(DeviceIntegrationConfigDTO configDTO) {
        List<DoorHaiKangDTO> doorHaiKangDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<DoorHaiKangDTO> recordList = null;
        do {
            recordList = this.requestRecord(pageNum, configDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            doorHaiKangDTOList.addAll(recordList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return doorHaiKangDTOList;
    }

    // 获取门禁在离线状态
    public List<DoorHaiKangDTO> pullDoorOnlineStatus(DeviceIntegrationConfigDTO configDTO) {
        JSONObject dataObject = generalHaiKangHandler.post(HaiKangConstant.DOOR_STATES_URL,
                new HashMap<>(1),
                configDTO.getProjectId(),
                configDTO.getProductId(),
                configDTO.getIpAndPort(),
                configDTO.getLoginName(),
                configDTO.getPassword(), configDTO.getTagId());
        JSONArray list = dataObject.getJSONArray("authDoorList");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.toJavaList(DoorHaiKangDTO.class);
    }

    private List<DoorHaiKangDTO> requestRecord(Integer pageNum, DeviceIntegrationConfigDTO configDTO) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("pageNo", pageNum);
        params.put("pageSize",500 );
        JSONObject dataObject = generalHaiKangHandler.post(HaiKangConstant.DOOR_SEARCH_URL,
                params,
                configDTO.getProjectId(),
                configDTO.getProductId(),
                configDTO.getIpAndPort(),
                configDTO.getAk(),
                configDTO.getSk(), configDTO.getTagId());
        JSONArray list = dataObject.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.toJavaList(DoorHaiKangDTO.class);
    }

}
